package com.tender.desensitization.factory.field;

import com.tender.desensitization.FieldReflectUtils;
import org.apache.commons.lang3.ClassUtils;
import org.springframework.core.ResolvableType;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.List;

import static com.tender.desensitization.GlobalRequestResponseAdvice.circleMap;

public class FieldAnnotationArrayProcessFactory implements FieldAnnotationDetectionFactory {

    private FieldAnnotationDetectionFactoryFacade factoryFacade;

    public FieldAnnotationArrayProcessFactory(FieldAnnotationDetectionFactoryFacade factoryFacade) {
        this.factoryFacade = factoryFacade;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isArray();
    }

    @Override
    public boolean processType(Field field) {
        ResolvableType resolvableType = ResolvableType.forField(field);

        while (resolvableType.isArray()) {
            resolvableType = resolvableType.getComponentType();
        }

        Class<?> resolve = resolvableType.resolve();
        if (ClassUtils.isPrimitiveOrWrapper(resolve) || String.class == resolve) {
            return false;
        }
        List<Field> allFields = FieldReflectUtils.getAllFields(resolve);

        if (!CollectionUtils.isEmpty(allFields)) {
            List<Class<?>> classList = circleMap.get(TopClassContext.getTopClass());
            // 存在类型嵌套
            if (classList.contains(resolve)) {
                return false;
            } else {
                classList.add(resolve);
            }
        }

        for (Field item : allFields) {
            FieldAnnotationDetectionFactory processFactory = factoryFacade.getProcessFactory(item.getType());
            if (null != processFactory) {
                if (processFactory.processType(item)) {
                    return true;
                }
            }
        }

        return false;
    }

}
